﻿using System.Text;
using System;
using Newtonsoft.Json;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Linq;

namespace CommonUtils
{
    public class JsonHelper
    {
        static Log log = new Log(typeof(JsonHelper).ToString());
        public static string JsonFileNameExtension = ".json";

        public static T DeSerialize<T>(string jsonString)
        {
             return DeSerializeByNewton<T>(jsonString);
        }

        public static string Serialize(object jsonObject)
        {
            return SerializeByNewton(jsonObject);
        }

        public static bool WriteToFile(object jsonObject, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("File name should not empty!");
            }

            if (null == jsonObject)
                return false;

            string jsonString = Serialize(jsonObject);
            try
            {
                using (System.IO.StreamWriter file = File.CreateText(fileName))
                {
                    file.Write(jsonString);
                    file.Close();
                }
            }
            catch (Exception ex)
            {
                log.E(ex);
            }

            return true;
        }

        public static T ReadFromFile<T>(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("File name should not empty!");
            }

            using (System.IO.StreamReader file = File.OpenText(fileName))
            {
                string jsonString = file.ReadToEnd();
                return (T)DeSerialize<T>(jsonString);
            }
        }
        
        private static string SerializeByNewton(object jsonObject)
        {
            try
            {
                return JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
            }
            catch (Exception ex)
            {
                new Log(typeof(JsonHelper).ToString()).E(ex);

            }
            return string.Empty;
        }

        private static T DeSerializeByNewton<T>(string jsonString)
        {
            return JsonConvert.DeserializeObject<T>(jsonString);
        }


        /// <summary>
        /// 将序列化的json字符串内容写入Json文件，并且保存
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="jsonConents">Json内容</param>
        public static void WriteJsonFile(string path, string jsonConents)
        {
            File.WriteAllText(path, jsonConents, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// 获取到本地的Json文件并且解析返回对应的json字符串
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        public static string GetJsonFile(string filepath)
        {
            string json = string.Empty;
            using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }

        /// <summary>
        /// 获取Json字符串中某个字段值
        /// </summary>
        /// <param name="strJson"></param>
        /// <param name="param">字段名</param>
        /// <returns></returns>
        public static string GetJsonReq(string strJson, string param, string defaultResult = "")
        {
            string ret = defaultResult;
            string str_req = "";

            str_req = strJson.Trim();
            if (str_req.Substring(0, 1).Equals("["))
                str_req = str_req.Remove(0, 1);
            if (str_req.Substring(str_req.Length - 1, 1).Equals("]"))
                str_req = str_req.Remove(str_req.Length - 1);

            ///* Propertie 方法
            var dyn = JsonConvert.DeserializeObject<JObject>(str_req);

            var propParams = dyn.Properties().FirstOrDefault(i => i.Name == param);
            if (propParams != null)
            {
                ret = propParams.Value.ToString();

            }

            return ret;
        }
    }
}
